# encoding:utf-8
import httpx
import json
from openai import AsyncOpenAI

from core.config import settings
from core.logger import log

async def baidu_ocr_table(base64_data: str=None,image_url: str= None):
    request_url = settings.BD_OCR_API_URL
    if base64_data:
        params = {"image": base64_data}
    elif image_url:
        params = {"url": image_url}
    else:
        log.error("请传入图片数据")
        return []
    # params = {"image": base64_data}
    access_token = settings.BD_API_ACCESS_TOKEN
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    async with httpx.AsyncClient() as client:
        response = await client.post(request_url, data=params, headers=headers,timeout=60)
    content = []
    table={}
    if response:
        if "tables_result" in response.json():
            tales = response.json()["tables_result"]
            for tale in tales:
                header = [text["words"] for text in tale["header"]]
                body = [text["words"] for text in tale["body"]]
                footer = [text["words"] for text in tale["footer"]]
                table["header"] = header
                table["body"] = body
                table["footer"] = footer
                content.append(table)
        else:
            tales = response.json()
            content.append(tales)
            log.info(tales)

    return content
async def analysis_ocr_reply(content):
    client = AsyncOpenAI(api_key="sk-e6e97623d99c4014b4da2b3f5b8ff19a", base_url="https://api.deepseek.com")

    response = await client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "你是一名金融助贷专员，请根据传入的信息(这些信息是ocr识别后的结果，里面的信息是一个整体)中提取“信贷交易违约概要”，“信贷交易授信及负债信息概要”，“机构查询记录明细”，分析客户征信报告问题及专业的建议。输出格式为：{},直接输出json格式信息，不得有多余废话"},
            {"role": "user", "content": json.dumps(content)},
        ]
    )
    return response.choices[0].message.content

